import React from 'react';
import { Spin } from 'antd';
import { isEqual, isEmpty } from 'lodash';
import { WeaErrorPage, WeaTools,WeaLocaleProvider } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
const { ls } = WeaTools;
import Title from './Title';
import MarqueeCom from '../common/MarqueeCom';
import NewsType from './NewsType';
import {formatData, formatDate, openLinkUrl,setContentviewHeight} from "../../util/common";
//内容组件
class EContent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            tabdata: props.edata.data,
            currentTab: props.edata.currenttab,
            counts: props.edata.counts,
            refresh: false,
        }
        this.handleTabData = this.handleTabData.bind(this);
        this.canOnclick = this.canOnclick.bind(this);
        this.handleOpen = this.handleOpen.bind(this);
        if(window.element_news_refresh && typeof window == 'object'){
            window.element_news_refresh[props.config.params.eid] = this.refreshTabData.bind(this);
        }else{
            let obj = {};
            obj[props.config.params.eid] = this.refreshTabData.bind(this);
            window.element_news_refresh = obj
        }
    }
    componentWillMount(){
        this.canOnclick();
    }
    componentWillReceiveProps(nextProps){
        const { isremembertab } = nextProps.config;
        if(!isEqual(nextProps, this.props)){
            if(isremembertab){
                this.setState({
                    tabdata: nextProps.edata.data,
                    counts: nextProps.edata.counts,
                    refresh: false,
                });
            }else {
                this.setState({
                    tabdata: nextProps.edata.data,
                    currentTab: nextProps.edata.currenttab,
                    counts: nextProps.edata.counts,
                    refresh: false,
                });
            }
        }
    }
    shouldComponentUpdate(nextProps, nextState){
        return !isEqual(this.state, nextState) || !isEqual(this.props, nextProps)
    }
    componentDidMount(){
        this.props.onRef(this);
    }

    refreshTabData(){
        const { currentTab } = this.state;
        this.setState({
            refresh: true,
        });
        this.handleTabData(currentTab);
    }

    handleTabData(tabid){
        const { params, isremembertab } = this.props.config;
        const { onChangeCanEdit } = this.props;
        const { currentTab } = this.state;
        const tabdata_local = ls.getJSONObj('tabdata-' + params.eid + '-' + tabid);
        this.setState({
            currentTab: tabid,
            refresh: tabid !== currentTab,
            tabdata: tabdata_local == null ? {} : tabdata_local,
        });
        if(isremembertab){
            let edata = ls.getJSONObj('edata-' + params.eid);
            if(edata){
                edata.currenttab = tabid;
                edata.data = tabdata_local;
                ls.set('edata-' + params.eid, edata);
            }
        }
        WeaTools.callApi('/api/portal/element/newstab', 'POST', {...params, tabid}).then(result => {
            const { docParams: docParams1={} } = result;
            const { docCatalogIds: docCatalogIds1 =[] } = docParams1;
            if(tabdata_local != null) {
                const { docParams={} } = tabdata_local;
                const { docCatalogIds =[] } = docParams;
                if(isEmpty(docCatalogIds1)){
                    onChangeCanEdit(false);
                }else  {
                    this.canOnclick(tabid, docCatalogIds1, true);
                }
            }else {
                this.canOnclick(tabid, docCatalogIds1);
            }
            ls.set('tabdata-' + params.eid + '-' + tabid, result);
            const { tabids = [], titles =[], tabsetting={} } = result;

            const { edata } = this.props;
            let { counts } = edata;
            if(tabid === this.state.currentTab){
                let currCount = "";
                if (result.data) {
                    for (var i = 0; i <tabids.length; i++) {
                        currCount = tabsetting.count;
                        if(currCount && currCount.noReadNum){
                            let noReadNum =parseInt(currCount.noReadNum);
                            if(noReadNum>99){
                                noReadNum=99;
                            }
                            if (tabids[i] === currentTab) {
                                counts[i].noReadNum = currCount.noReadNum;
                            }
                        }else if(currCount && currCount.isHaveNoRead) {
                            let isHaveNoRead =currCount.isHaveNoRead;
                            if (tabids[i] === currentTab) {
                                counts[i].isHaveNoRead = currCount.isHaveNoRead;
                            }
                        }
                    }
                }

                this.setState({
                    tabdata: result,
                    refresh: false,
                    counts: counts
                });
                if((!tabsetting.count.isHaveNoRead || tabsetting.count.isHaveNoRead=='0')){
                    $(`.homepage #titleContainer_${params.eid} .rc-tabs-nav-container .rc-tabs-nav-wrap .tab2selected`).find("div.portal-new-unreadpoint").remove();
                }
                if(isremembertab){
                    let edata = ls.getJSONObj('edata-' + params.eid);
                    if(edata){
                        edata.currenttab = tabid;
                        edata.data = result;
                        ls.set('edata-' + params.eid, edata);
                    }
                }
            }
        });
    }
    handleOpen(){
        const { tabdata } = this.state;
        const { tabsetting = {} } = tabdata;
        const { catalogId, catalogIds } = tabsetting;
        if(catalogId){
            openLinkUrl('/spa/document/index.jsp?secid='+catalogId+'&isEdit=1&moudleFrom=portal','2');
        }else{
            let catalogIdsNew = catalogIds;
            if (catalogIds.substr(0,1)==',') {
                catalogIdsNew=catalogIds.substr(1);
            }
            openLinkUrl('/spa/document/static/index.html#/main/document/add?openNewWindow=0&moudleFrom=portal&secids='+catalogIdsNew,'2');
        }
    }
    canOnclick(currentTab = this.state.currentTab, docCatalogIds1, bol){
        const { config, edata, onChangeCanEdit } = this.props;
        const { tabdata = {} } = this.state;
        const { data } = edata;
        const { eid } = config.params;
        const { docParams ={} } = tabdata;
        const { docCatalogIds=[] } = docParams;
        if((docCatalogIds && docCatalogIds.length > 0) || (docCatalogIds1 && docCatalogIds1.length > 0)){
            let rightArr = ls.getJSONObj('portal-doc-right');
            let params = {ids: docCatalogIds.join()};
            if(docCatalogIds1) {
                params = {ids: docCatalogIds1.join()};
            }
            if(rightArr == null){
                if(!this.isTrue){
                    this.isTrue = true;
                    const _self = this;
                    WeaTools.callApi('/api/portal/elementsetdoc/docsetright', 'POST', params).then(result => {
                        let right = result.canEdit == 'true' ? true : false ;
                        onChangeCanEdit(right);
                        ls.set('portal-doc-right', [{eid: eid, tabid: currentTab, data: formatDate(new Date(), "yyyy-MM-dd"),right: right}]);
                        _self.isTrue = false;
                    });
                }
            }else{
                let isHave = false;
                if(bol){
                    rightArr.map((item)=>{
                        if(item !== null && item.eid == eid && item.tabid == currentTab){
                            onChangeCanEdit(item.right);
                            isHave = true;
                            return;
                        }
                    });
                }
                if(!isHave){
                    WeaTools.callApi('/api/portal/elementsetdoc/docsetright', 'POST', params).then(result => {
                        let right = result.canEdit == 'true' ? true : false ;
                        onChangeCanEdit(right);
                        rightArr.push({eid: eid, tabid: currentTab,data: formatDate(new Date(), "yyyy-MM-dd"), right: right });
                        ls.set('portal-doc-right', rightArr);
                    });
                }
            }
        }else {
            onChangeCanEdit(false);
        }
    }
    render() {
        const { config, edata, handleRefresh, handleDelete, fontSizeMp } = this.props;
        const { tabdata, currentTab, refresh, counts } = this.state;
        const { tabids = [], titles =[], esetting={} } = edata;
        const { tabsetting = {}, dataColoums=[] } = tabdata;
        const { eid, ebaseid } = config.params;
        let { fontStyle} = config.item;
        const { contentview = {},header } = config.item;
        if(!isEmpty(fontSizeMp)) fontStyle = fontSizeMp;
        esetting.fontStyle = fontStyle;
        esetting.dataColoums = dataColoums;
        let cstyle = {height: contentview.style.height,overflow: "auto"};
        if(header.displayPosition && header.displayPosition == 'bottom'){
            if(tabids && tabids.length > 1 || tabids && tabids.length == 1 && esetting.isAlwaysShow=='1'){
                if(contentview.style.height){
                    if(esetting.tabstyle == '1' && esetting.tabvalue){
                        cstyle = setContentviewHeight(contentview.style.height,esetting.tabvalue)
                    }else{
                        cstyle = {height: parseInt(contentview.style.height)-32+"px",overflow: "auto"};
                    }   
                }else {
                    cstyle = {height: contentview.style.height,overflow: "auto"};
                }
                let elementH=parseInt(contentview.style.height)-parseInt($(`#titleContainer_${eid}`).css('height'));
                if(elementH!=parseInt(cstyle.height)){
                    if(elementH<parseInt(cstyle.height)){
                        cstyle.height=elementH+"px";
                    }
                }
            }
        }


        let contentHtml = <div/>;
        let more = '';
        let tabdata_img = {};
        if(!isEmpty(tabdata)){
            tabdata_img = _.cloneDeep(tabdata);
            tabdata_img.tabsetting.imgs=[];
        }
        if (tabdata && tabdata.data) {
            more = tabsetting.more;
            contentHtml = <MarqueeCom ecId={`${this && this.props && this.props.ecId || ''}_MarqueeCom@k5oxoc`} tabdata={!refresh ? tabdata: tabdata_img} eid={eid} scolltype={tabsetting.rollDirection} scrollSpeed={tabsetting.scrollSpeed} showModeId={tabsetting.showModeId} ebaseid={ebaseid}><NewsType ecId={`${this && this.props && this.props.ecId || ''}_NewsType@vidhkp`} contentview={contentview} eid={eid} data={!refresh ? tabdata: tabdata_img} esetting={esetting} /></MarqueeCom>
        }
        const _titleProps = {
            currentTab,
            config,
            titles,
            tabids,
            handleRefresh,
            handleDelete,
            more,
            counts: counts,
            isShowSettingShowType: tabsetting.isShowSettingShowType,
            eMoreAddress: tabsetting.eMoreAddress,
            eMoreShowType: tabsetting.eMoreShowType,
            fontSizeMp,
            tabwidth: esetting.tabwidth,
            methodvalue: esetting.methodvalue,
            isAlwaysShow: esetting.isAlwaysShow,
            tabstyle: esetting.tabstyle,
            tabvalue: esetting.tabvalue,
            handleTabData: this.handleTabData
        }
        return <div>
            <Title ecId={`${this && this.props && this.props.ecId || ''}_Title@4ct8cy`} {..._titleProps}/>
            <div className="tabContant" id={`tabcontant_${eid}`} style={{height: cstyle.height}}>
                <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@0xw45a`} spinning={refresh}>{contentHtml}</Spin>
            </div>
        </div>;
    }
}

class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
        return ( <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@yf56aa`} msg = { hasErrorMsg ? this.props.error : getLabel(385218,"对不起，该页面异常，请联系管理员！") }/>
        );
    }
}
EContent = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(EContent);
export default EContent;
